<template>
  <view class="contain ">
    <view class="top flex">
      <view class="left">
        <view class="tag">{{ data.detail.category_name }}</view>
      </view>
      <view class="right">
        <view style="font-size: 36rpx;font-weight: 500;">{{ data.detail.title }}</view>
        <view class="flex" style="align-items: center;padding-top: 12rpx;">
          <u-badge :isDot="true" type="warning" max="99"></u-badge>
          <text style="padding-left: 12rpx;color: rgba(0,0,0,0.9);line-height: 60rpx;">
            {{ data.detail.sign_status_name }}
          </text>
        </view>
        <view style="font-size: 28rpx;color: color: rgba(0,0,0,0.6);line-height: 50rpx;">
          签署截止日期：{{ data.detail.end_date }}
        </view>
        <view style="font-size: 28rpx;color: color: rgba(0,0,0,0.6);line-height: 50rpx;">
          备注：{{ data.detail.remark }}
        </view>
      </view>
    </view>
    <view class="bg-color p-l-r-32 flex-1">
      <view class="m-t-32 m-b-100">
        <view>签署人信息</view>
        <view class="flex sign" style="" v-for="(item,index) in data.detail.signers" :key="index">
          <view class="list">
            <view class="tag" v-if="item.signer_type == 'self'">发起方</view>
            <view class="tag" style="background-color: #00A870;" v-else>签署方</view>
            <view class="sign_b">
              <view class="sign_s">
                <view>
                  <image class="avatar" v-if="item.signer_type == 'self'"
                         src="../../static/images/self.png">
                  </image>
                  <image class="avatar" v-else src="../../static/images/signer.png"></image>
                </view>
                <view>
                  <text v-if="item.signer_user_type=='user'">{{ item.company_name }}</text>
                  <view style="display: flex;">
                    <!-- <text v-if="item.signer_user_type=='user'">{{ item.company_name }}【{{ item.name }}】</text> -->
                    <text>{{ item.name }}</text>
                    <text
                        :style='item.signer_type == "self"?"color:#4787f0":"color:#00A870"'>
                      &nbsp;&nbsp;(关键字：{{ item.key_word }})
                    </text>
                  </view>
                  <text>{{ item.cellphone_secret }}</text>
                  <!-- <text>{{ item.sign_status_name }}</text> -->
                </view>
              </view>
              <image class="icon" v-if="item.sign_status == 'signed'" src="../../static/images/sign.png">
              </image>
              <image class="icon" v-else src="../../static/images/sign_.png"></image>
            </view>
          </view>
        </view>


        <view class="m-t-32 m-b-100">企业签署人</view>
        <view class="flex sign">
          <view class="list" v-if="data.detail.signer_user.id > 0">
            <view class="tag">企业签署人</view>
            <view class="sign_b">
              <view class="sign_s">
                <view>
                  <image class="avatar" src="../../static/images/self.png"></image>
                </view>
                <view>
                  <text>{{ data.detail.signer_user.show_info }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="m-t-32 m-b-100">企业审核人</view>
        <view class="flex sign">
          <view class="list" v-if="data.detail.audit_user.id > 0">
            <view class="tag">企业审核人</view>
            <view class="sign_b">
              <view class="sign_s">
                <view>
                  <image class="avatar" src="../../static/images/self.png"></image>
                </view>
                <view>
                  <text>{{ data.detail.audit_user.show_info }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="m-t-32 m-b-100">抄送人</view>
        <view class="flex sign" v-if="data.detail.recipient_members.length > 0"
              v-for="(item,index) in data.detail.recipient_members" :key="index">
          <view class="list">
            <view class="tag">抄送人</view>
            <view class="sign_b">
              <view class="sign_s">
                <view>
                  <image class="avatar" src="../../static/images/self.png"></image>
                </view>
                <view>
                  <text>{{ item.label }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

      </view>
      <u-line class="m-t-32"></u-line>
      <view class="file-list m-t-32" v-if="data.detail.file">
        <view class="" style="padding-top: 32rpx;">合同文件(需双方签署)</view>
        <view class="file-list-item flex" v-for="(item,index) in data.detail.file" :key="index"
              @click="policyPreview(item,1)">
          <image src="../../static/images/file-paste_normal.png"></image>
          <view class="line-clamp-1">{{ item.org_name }}</view>
          <view
              v-if="!fileReadeFinish && ((data.detail.login_sign_status && data.detail.login_sign_status == 'pending') || (!data.detail.login_sign_status && data.detail.sign_status == 'pending')) "
              style="color:red">（未读）
          </view>
          <view v-else>（已读）</view>
          <view style="text-decoration: underline;" v-if="item.set_data.length>0"
                @click.stop="contractSignC.init(item,index)">签署
          </view>
        </view>
      </view>
      <view class="file-list m-t-32" v-if="data.detail.signer_file.length>0">
        <view class="">协议文件(仅签署人签署)</view>
        <view class="file-list-item flex" v-for="(item,index) in data.detail.signer_file" :key="index"
              @click="policyPreview(item,2)">
          <image src="../../static/images/file-paste_normal.png"></image>
          <view class="line-clamp-1">{{ item.org_name }}</view>
          <view
              v-if="!signerFileReadeFinish && ((data.detail.login_sign_status && data.detail.login_sign_status == 'pending') || (!data.detail.login_sign_status && data.detail.sign_status == 'pending')) "
              style="color:red">（未读）
          </view>
          <view v-else>（已读）</view>
        </view>
      </view>
      <view class="file-list m-t-32" v-if="data.detail.other_file.length>0">
        <view class="">附件(无需签署)</view>
        <view class="file-list-item flex" v-for="(item,index) in data.detail.other_file" :key="index"
              @click="policyPreview(item,3)">
          <image src="../../static/images/file-paste_normal.png"></image>
          <view class="line-clamp-1">{{ item.org_name }}</view>
          <view
              v-if="!otherFileReadeFinish && ((data.detail.login_sign_status && data.detail.login_sign_status == 'pending') || (!data.detail.login_sign_status && data.detail.sign_status == 'pending')) "
              style="color:red"> （未读）
          </view>
          <view v-else>（已读）</view>
        </view>
      </view>
      <view class="file-list m-t-32 m-b-150" v-if="data.detail.is_annex == 1">
        <view class="" style="padding-top: 32rpx;">证明
          <view @click="data.menuShow = true">
            <u--text
                v-if="data.detail.signer_sign_status == 1" text="上传文件" type="primary"></u--text>
          </view>
        </view>
        <view class="file-list-item flex" v-for="(item,index) in annex_file" :key="index">
          <view class="flex" style="margin-right: 10rpx;" @click.stop="policyPreview_(item)">
            <image src="../../static/images/file-paste_normal.png"></image>
            <view class="line-clamp-1">{{ item.org_name }}</view>
          </view>
          <u-icon v-if=" data.detail.login_sign_status == 'pending'" name="close" color="rgba(0, 0, 0, 0.60)"
                  size="16" style="margin-top: 6rpx;" @click.stop="delAnnexFile(index)"></u-icon>
        </view>
      </view>
      <contract-sign ref="contractSignC" @return-data="returnData"></contract-sign>
    </view>
    <view style="position: fixed;bottom: 0;width: 100%;z-index: 999;" v-if="data.detail.signer_sign_status == 1">
      <text class="flex bottom-button help"
            v-if="!fileReadeFinish || !otherFileReadeFinish || !signerFileReadeFinish">请先查看文件！！
      </text>
      <view class="flex bottom-button">
        <u-button type="primary" text="手绘签署" class="custom-style" @click="isAuthentication(1)"
                  :disabled="!fileReadeFinish || !otherFileReadeFinish || !signerFileReadeFinish"
                  :customStyle="{borderRadius:'0rpx',border:'none',padding:'0',height:'auto'}"></u-button>
        <u-button type="primary" class="custom-style" @click="isAuthentication(2)"
                  :disabled="!fileReadeFinish || !otherFileReadeFinish || !signerFileReadeFinish"
                  :customStyle="{borderRadius:'0rpx',border:'none',padding:'0',height:'auto'}">印章签署
        </u-button>
      </view>
    </view>
    <view class="signature" v-if="control.signaAuthShow">
      <signa-ture @getImg="getImgAuth" @close="control.signaAuthShow = false"></signa-ture>
    </view>
    <key-board ref="keyboardC" @return-pass="returnPass"></key-board>
    <seal-list ref="sealListC" @return-seal="returnSeal"></seal-list>

    <view class="editBtn" style="bottom: 1000rpx;"
          v-if="data.detail.edit_status =='1'"
          @click="goNav('/pages/contract/enterprise/edit?contract_id='+data.detail.id)">编辑合同
    </view>

    <view v-if="data.detail.revoke_status== '1'" class="editBtn"
          style="bottom:800rpx;"
          @click="revoke">撤销合同
    </view>

    <view v-if="data.detail.disuse_status== '1'" class="editBtn"
          style="bottom:600rpx;"
          @click="disuse">废弃合同
    </view>


    <u-action-sheet :actions="data.menuInfo.list" @select="select" @close="close" cancelText="取消"
                    :title="data.menuInfo.title" :closeOnClickOverlay="true" :closeOnClickAction="true" :round="24"
                    :show="data.menuShow"></u-action-sheet>
  </view>
</template>
<script setup>
import SignaTure from "@/components/signature.vue";
import KeyBoard from "@/components/keyboard.vue";
import ContractSign from "@/components/contract-sign.vue";
import sealList from "@/components/seal-list.vue";
import {
  membercontractDetail,
  contractRevoke,
  contractDisuse
} from "@/api/module/contract.js"
import {
  useStore
} from 'vuex';
import {
  onLoad
} from "@dcloudio/uni-app";
import {
  reactive,
  ref
} from "vue";
import {
  previewfile,
  previewImage,
  previewVideo,
  handlesuffix
} from "@/utils/article/fileRead";
import {
  arrayPluck,
  eqLength,
  goNav,
  inArray,
  msg,
  upload,
  goSwitchTab
} from "@/utils/common";
import {
  authentication,
  jump
} from "@/utils/contract/isAuthentication";
import {
  uploadImageBase64
} from "@/api/module/common";
import {
  contractSign,
  userContractSign,
  keySign
} from "@/api/module/contract";

const sealListC = ref();
const contractSignC = ref();
const store = useStore()
const data = reactive({
  signer_type: 'self',
  member_contract_id: 0,
  detail: {},
  readFileId: [],
  readOtherFileId: [],
  readSignerFileId: [],
  member_seal_id: 0,
  menuShow: false,
  menuInfo: {
    title: '选择文件',
    list: [{
      name: '上传文件',
      type: 'file',
    }, {
      name: '上传图片/视频',
      type: 'media',
    }]
  },
  uploadLength: 0,
  uploadIndex: 0,
})
const control = ref({
  signaAuthShow: false,
})
const keyboardC = ref();
const annex_file = ref([]);
const fileReadeFinish = ref(false)
const otherFileReadeFinish = ref(false)
const signerFileReadeFinish = ref(false)
const pxToRpx = (px) => {
  let scale = uni.upx2px(100) / 100;
  const scale_ = parseFloat((600 / (uni.getSystemInfoSync().screenWidth - uni.upx2px(64))).toFixed(2));
  return (px / scale_) / scale
}
onLoad((options) => {
  data.signer_type = options.signer_type;
  data.member_contract_id = options.member_contract_id;
  queryDetail();
});
const returnData = (e) => {
  data.detail.file[e.index] = e.file;
}
//印章选择
const seal = () => {
  sealListC.value.open()
}
//印章选择回调
const returnSeal = (seal_id) => {
  if (seal_id < 1) {
    msg('请选择签署印章');
    return false;
  }
  data.member_seal_id = seal_id;
  userSign({
    signer_type: data.signer_type,
    member_contract_id: data.detail.id,
    member_seal_id: data.member_seal_id,
    annex_file: arrayPluck(annex_file.value, 'id'),
  });

}
const queryDetail = () => {
  //企业
  membercontractDetail({
    member_contract_id: data.member_contract_id
  }).then(res => {
    data.detail = res;
    if (res.other_file.length < 1) {
      otherFileReadeFinish.value = true
    }
    if (!res.signer_file.length) {
      signerFileReadeFinish.value = true
    }
    if (res.file.length < 1) {
      otherFileReadeFinish.value = true
    }
    annex_file.value = res.annex_file;
  })
}
const isAuthentication = async (status) => {
  if (!await authentication(store.state.userType)) {
    return
  }
  if (annex_file.value.length < 1 && data.detail.is_annex == 1) {
    msg('请上传证明');
    return;
  }
  switch (status) {
    case 1:
      // goNav('/pages/contract/enterprise/signPage?signer_type=' + data.signer_type + '&id=' + data.detail.member_contract_id
      //     + '&annex_file=' + arrayPluck(annex_file.value, 'id').join(','));
      control.value.signaAuthShow = true; //手绘签署 打开签名
      break;
    case 2:
      // goNav('/pages/contract/enterprise/sealList?signer_type=' + data.signer_type +
      //     '&member_contract_id=' + data.detail.id + '&annex_file=' + arrayPluck(annex_file.value,
      //         'id').join(','))
      seal();
      break
  }
}
const getImgAuth = (url) => {
  const tempArr = url.split('.');
  const tempPathArr = url.split('/');
  const tempExt = tempArr[tempArr.length - 1];
  const tempName = tempPathArr[tempPathArr.length - 1];
  upload({
    tempName: tempName,
    tempPath: url,
    tempExt: tempExt,
    // turn: 90,
  }, function (response) {
    userSign({
      signer_type: data.signer_type,
      member_contract_id: data.detail.id,
      member_seal_id: 0,
      member_seal_image: response.res.url,
      annex_file: arrayPluck(annex_file.value, 'id'),
    });
  });
  control.value.signaAuthShow = false
}
const userSign = (params) => {
  keyboardC.value.open(params)
  // uni.showModal({
  // 	title: '签署密码',
  // 	content: '',
  // 	editable: true, //是否显示输入框
  // 	placeholderText: '请输入签署密码', //输入框提示内容
  // 	confirmText: '确认',
  // 	cancelText: '取消',
  // 	success: (res) => {
  // 		if (res.confirm) {
  // 			params.password = res.content;
  // 			userContractSign(params).then(res => {
  // 				if (res.status_code == 501) {
  // 					jump(store.state.userType)
  // 				}
  // 				msg('签署成功');
  // 				queryDetail();
  // 			})
  // 		}
  // 	}
  // });
}
const revoke = () => {
  uni.showModal({
    title: '撤销合同',
    content: '确定要撤销该合同吗？',
    confirmText: '确认',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        contractRevoke({
          member_contract_id: data.member_contract_id
        }).then(res => {
          msg('撤销成功');
          goSwitchTab('/pages/contract/index')
        })
      }
    }
  });
}

const disuse = () => {
  uni.showModal({
    title: '废弃合同',
    content: '确定要废弃该合同吗？',
    confirmText: '确认',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        contractDisuse({
          member_contract_id: data.member_contract_id
        }).then(res => {
          msg('废弃成功');
          goSwitchTab('/pages/contract/index')
        })
      }
    }
  });
}
const returnPass = (data) => {
  keySign(data).then(res => {
    if (res.status_code == 501) {
      jump(store.state.userType)
    }
    keyboardC.value.close()
    msg('签署成功');
    queryDetail();
  })
}
const policyPreview = (info, type) => {
  switch (type) {
    case 1:
      if (!inArray(info.id, data.readFileId)) {
        data.readFileId.push(info.id)
      }
      if (eqLength(data.readFileId, data.detail.file)) {
        fileReadeFinish.value = true
      }
      previewfile(info.pdf_url ? info.pdf_url : info.path_url)
      break;
    case 2:
      if (!inArray(info.id, data.readSignerFileId)) {
        data.readSignerFileId.push(info.id)
      }
      if (eqLength(data.readSignerFileId, data.detail.signer_file)) {
        signerFileReadeFinish.value = true
      }
      previewfile(info.pdf_url ? info.pdf_url : info.path_url)
      break;
    case 3:
      if (!inArray(info.id, data.readOtherFileId)) {
        data.readOtherFileId.push(info.id)
      }
      if (eqLength(data.readOtherFileId, data.detail.other_file)) { //判断是否阅读完所有文件
        otherFileReadeFinish.value = true
      }
      previewfile(info.pdf_url ? info.pdf_url : info.path_url)
      break;
  }
  // switch (handlesuffix(info.org_name)) {
  // 	case 1: //文件
  // 		if (!inArray(info.id, data.readFileId)) {
  // 			data.readFileId.push(info.id)
  // 		}
  // 		if (eqLength(data.readFileId, data.detail.file)) { //判断是否阅读完所有文件
  // 			fileReadeFinish.value = true
  // 		}
  // 		previewfile(info.pdf_url ? info.pdf_url : info.path_url);
  // 		break;
  // 	case 2: // 图片
  // 		if (!inArray(info.id, data.readOtherFileId)) {
  // 			data.readOtherFileId.push(info.id)
  // 		}
  // 		if (eqLength(data.readOtherFileId, data.detail.other_file)) {
  // 			otherFileReadeFinish.value = true
  // 		}
  // 		previewImage(info.path_url)
  // 		break;
  // }
}
const policyPreview_ = (info) => {
  const fileSuffix = ['doc', 'docx', 'pdf', 'pptx', 'ppt', 'xls', 'xlsx', 'txt', 'rar', 'zip', 'exe']
  const imageSuffix = ['png', 'jpg', 'jpeg', 'gif', 'bmp']
  const videoSuffix = ['avi', 'mov', 'wmv', 'mp4']
  var type = info.type ? info.type : info.path_url.substring(info.path_url.length - 6).split('.')[1];
  if (fileSuffix.indexOf(type) >= 0) {
    previewfile(info.url ? info.url : info.path_url)
  } else if (imageSuffix.indexOf(type) >= 0) {
    previewImage(info.url ? info.url : info.path_url)
  } else if (videoSuffix.indexOf(type) >= 0) {
    previewVideo(info.url ? info.url : info.path_url)
  }
}
const delAnnexFile = (index) => {
  annex_file.value.splice(index, 1);
}
// const uploadFile = () => { //选择图片  转base64
// 	uni.chooseImage({
// 		count: 5, //上传图片数量
// 		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
// 		sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有
// 		success: (chooseImageRes) => {
// 			//tempFilePaths 图片的本地文件路径列表
// 			const tempFilePaths = chooseImageRes.tempFilePaths[0];
// 			uni.getFileSystemManager().readFile({
// 				filePath: tempFilePaths, // 要读取的文件路径
// 				encoding: 'base64', // 编码格式
// 				success: function(res) {
// 					let imageParams = {
// 						ext: 'png',
// 						content: res.data,
// 						org_name: new Date().getTime() + '.png'
// 					}
// 					uploadImageBase64(imageParams).then(res => {
// 						annex_file.value.push(res);
// 						// let params = {
// 						//   id: data.userInfo.id,
// 						//   image
// 						// }
// 					})
// 				}
// 			})
// 		}
// 	});
// }
const close = () => {
  data.menuShow = false;
}
const select = (e) => {
  const type = e.type
  switch (type) {
    case 'file':
      uploadFile()
      break;
    case 'media':
      uploadMedia()
      break;
    default:
      break;
  }
}
//文件上传
const uploadFile = () => {
  wx.chooseMessageFile({
    count: 9,
    type: 'file',
    extension: ['doc', 'docx', 'pdf', 'pptx', 'ppt', 'xls', 'xlsx', 'txt'],
    success: function (tempFilePaths) {
      data.uploadLength = tempFilePaths.tempFiles.length;
      data.uploadIndex = 0;
      uploadFn(tempFilePaths.tempFiles, 1)
    }
  });
}
//图片或视频上传
const uploadMedia = () => {
  uni.chooseMedia({
    count: 9,
    mediaType: ['image', 'video'],
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (tempFilePaths) => {
      data.uploadLength = tempFilePaths.tempFiles.length;
      data.uploadIndex = 0;
      uploadFn(tempFilePaths.tempFiles, 2)
    }
  });
}
const uploadFn = (uploadArr, type) => {
  const tempFilePath = uploadArr[data.uploadIndex];
  console.log(tempFilePath, 33)
  if (type == 1) {
    var tempName = tempFilePath['name'];
    var tempPath = tempFilePath['path'];
  } else {
    var tempPath = tempFilePath['tempFilePath'];
    var tempNameArr = tempPath.split('/');
    var tempName = tempNameArr[tempNameArr.length - 1];
  }
  const tempArr = tempName.split('.');
  const tempExt = tempArr[tempArr.length - 1];
  upload({
    tempName: tempName,
    tempPath: tempPath,
    tempExt: tempExt,
  }, function (response) {
    annex_file.value.push(response.res)
    console.log(response, 66);
    data.uploadIndex++;
    if (data.uploadIndex < data.uploadLength) {
      uploadFn(uploadArr, type)
    }
  });
}
</script>
<style lang="scss" scoped src="/static/css/contract/detail.scss"></style>